package com.woniuxy.student.controller;

import com.woniuxy.student.consumer.DivideStudentMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author weizihan
 * @Date 2020/7/21 2020/7/21
 * @Description 将rabbitmq消息推送到前端--websocket
 * @Since version-1.0
 */
@Component
@ServerEndpoint("/websocket")
@Slf4j
public class DivideStudent {
    private Session session;
    private static Set<DivideStudent> divideStudents = new CopyOnWriteArraySet<>();

    @Autowired
    private DivideStudentMessage divideStudentMessage;
    //连接时
    @OnOpen
    public void opOpen(Session session){
        this.session = session;
        divideStudents.add(this);
        log.info("websocket有新的连接，总数为{}",divideStudents.size());
    }

    //关闭
    @OnClose
    public void onClose(){
        divideStudents.remove(this);
        log.info("websocket连接断开，总数{}",divideStudents.size());
    }

    //收到消息
    @OnMessage
    public void onMessage(String message){
        log.info("webSocket消息，收到客户端发来的消息：{}",message);
    }

    //发送消息
    public void senMessage(String message){
        for (DivideStudent divideStudent:divideStudents
             ) {
            log.info("推送广播消息，message={}",message);
            try {
                    divideStudent.session.getBasicRemote().sendText(message);

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
